<template>
    <div class="sysinterface">
        <div class="apiedit">
            <a-button type="primary" :loading="confirmLoading" @click="handlerSave">
                {{ $ti18('rxForm.saveBtn', '保存') }}
            </a-button>
        </div>
        <div>
            <a-form :form="form" layout="vertical" class="rx-sys-form">
                <a-collapse default-active-key="1" expandIconPosition="right">
                    <a-collapse-panel key="1" :header="i18n('apiPreview.basicSetting','基本设置')">
                        <div style="padding: 10px">
                            <a-form-item style="display:none">
                                <a-input v-decorator="['apiId']"/>
                            </a-form-item>
                            <a-row :gutter="[24,12]">
                                <a-col :span="12">
                                    <a-form-item :label="i18n('form.apiKey','接口别名')">
                                        <a-input :placeholder="i18n('form.apiKey','接口别名')"
                                                 v-decorator="['apiKey', {rules: [{required: true, message: i18n('form.apiKey','请输入接口别名','input')}]}]"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item :label="i18n('form.apiName','接口名称')">
                                        <a-input :placeholder="i18n('form.apiName','接口名称')"
                                                 v-decorator="['apiName', {rules: [{required: true, message: i18n('form.apiName','请输入接口名称','input')}]}]"/>
                                    </a-form-item>
                                </a-col>

                                <a-col :span="12">
                                    <a-form-item :label="i18n('form.classification','接口分类')">
                                        <a-select
                                            v-decorator="['classificationId', {rules: [{required: true, message: i18n('form.classification','接口分类','select')}]}]"
                                            :options="classificationOptions"/>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item :label="i18n('form.interfaceType','接口类型')">
                                        <a-select
                                            v-decorator="['apiType',{rules: [{ required: true, message: i18n('form.interfaceType','请选择接口类型','select') }]}]"
                                            @change="apiTypeChange">
                                            <a-select-option value="RESTful">
                                                RESTful
                                            </a-select-option>
                                            <a-select-option value="SOAP">
                                                SOAP
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <a-col :span="24">
                                    <a-form-item>
                                            <span slot="label">
                                                {{ i18n('form.interfacePath', '接口路径') }}
                                                <a-tooltip>
                                                    <template slot="title">
                                                        1.{{ i18n('apiEdit.apiPathExplain', '支持动态路由,例如') }}:/api/user/${id}
                                                    </template>
                                                    <a-icon type="question-circle-o"/>
                                                </a-tooltip>
                                            </span>
                                        <a-input-group compact>
                                            <a-select v-show="apiType=='RESTful'" style="width:100px;"
                                                      v-decorator="['apiMethod', { initialValue: 'GET',rules: [{ required: apiType=='RESTful', message: i18n('apiEdit.inputApiPath','请输入接口域名路径') }] }]"
                                                      @change="methodChange">
                                                <a-select-option value="GET">
                                                    GET
                                                </a-select-option>
                                                <a-select-option value="POST">
                                                    POST
                                                </a-select-option>
                                                <a-select-option value="PUT">
                                                    PUT
                                                </a-select-option>
                                                <a-select-option value="DELETE">
                                                    DELETE
                                                </a-select-option>
                                            </a-select>
                                            <a-tooltip style="padding: 0px">
                                                <template slot="title">
                                                    {{ i18n('apiEdit.apiPathDesc', '接口基本路径，可在 项目设置 里修改') }}
                                                </template>
                                                <a-input class="basePath" style="width:120px;top: 0px;" :disabled="true"
                                                         v-model="basePath">
                                                    <span slot="addonAfter"></span>
                                                </a-input>
                                            </a-tooltip>
                                            <a-input style="width:calc(100% - 220px);padding-left:10px;margin: 0px"
                                                     v-decorator="['apiPath',{rules: [{ required: true, message: i18n('apiEdit.inputApiPath','请输入接口域名路径') }]}]"
                                                     @change="changeApiPath"/>
                                        </a-input-group>
                                        <a-row v-for="(param,index) in pathParams" :key="index"
                                               style="position:relative">
                                            <a-col :span="4">
                                                <a-input v-model="param.paramName" :disabled="true"/>
                                            </a-col>
                                            <a-col :span="4">
                                                <a-select v-model="param.paramSource" :options="sourceOptions"/>
                                            </a-col>
                                            <a-col :span="4" v-if="param.paramSource!='param'">
                                                <a-input :placeholder="i18n('apiEdit.paramValue','参数值')"
                                                         v-model="param.paramValue"
                                                         v-if="param.paramSource == 'fixedVar'"/>
                                                <a-input-group v-if="param.paramSource == 'script'" compact>
                                                    <a-input style="width:73%;" v-model="param.paramValue"
                                                             :disabled="true"/>
                                                    <a-button @click="openScriptQuery(param)">...</a-button>
                                                </a-input-group>
                                                <a-select v-if="param.paramSource=='constantVar'"
                                                          v-model="param.paramValue"
                                                          :options="constantField"></a-select>
                                            </a-col>
                                            <a-col :span="param.paramSource!='param'?12:16">
                                                <a-input :placeholder="i18n('apiPreview.remarks','备注')"
                                                         v-model="param.paramDesc"/>
                                            </a-col>
                                        </a-row>
                                    </a-form-item>
                                </a-col>

                                <a-col :span="12">
                                    <a-form-item :label="i18n('apiEdit.isLog','是否记录日志')">
                                        <a-radio-group v-decorator="['isLog']" button-style="solid">
                                            <a-radio-button value="YES">
                                                {{ i18n('apiPreview.yes', '是') }}
                                            </a-radio-button>
                                            <a-radio-button value="NO">
                                                {{ i18n('apiPreview.no', '否') }}
                                            </a-radio-button>
                                        </a-radio-group>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item :label="i18n('form.status','状态')">
                                        <a-radio-group v-decorator="['status']" button-style="solid">
                                            <a-radio-button value="DONE">
                                                {{ i18n('isProjectStatusMap.enable', '启用') }}
                                            </a-radio-button>
                                            <a-radio-button value="UNDONE">
                                                {{ i18n('isProjectStatusMap.disable', '禁用') }}
                                            </a-radio-button>
                                        </a-radio-group>
                                    </a-form-item>
                                </a-col>
                            </a-row>

                        </div>
                    </a-collapse-panel>
                </a-collapse>
                <a-collapse style="margin-top: 10px" default-active-key="2" expandIconPosition="right">
                    <a-collapse-panel key="2" :header="i18n('apiEdit.requestParamSet','请求参数设置')">
                        <div style="padding: 10px">
                            <div>
                                <a-radio-group v-model="paramType">
                                    <a-radio-button :value="paramTypeOpt.value" v-for="paramTypeOpt in paramTypeOptions">
                                    {{ paramTypeOpt.label }}
                                    </a-radio-button>
                                </a-radio-group>
                            </div>
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item v-show="paramType=='Body'">
                                        <a-radio-group v-model="apiDataType" :options="contentTypeOptions" style="margin-top: 6px;"/>
                                        <div v-if="apiDataType=='form'">
                                            <a-button type="primary" @click="addFormParam" style="margin: 10px 0">
                                                {{ i18n('apiEdit.addFromParamBtn', '添加Form参数') }}
                                            </a-button>
                                            <vuedraggable v-model="bodyData">
                                                <transition-group>
                                                    <a-row :gutter="[0,10]" :key="index" v-for="(body,index) in bodyData"
                                                           style="position:relative">
                                                        <a-col :span="4">
                                                            <a-input style="width: calc(100% - 10px)" placeholder="name"
                                                                     v-model="body.paramName"/>
                                                        </a-col>
                                                        <a-col :span="3">
                                                            <a-select style="width: calc(100% - 10px)"
                                                                      v-model="body.paramRequire"
                                                                      :options="requireOptions"/>
                                                        </a-col>
                                                        <a-col :span="4">
                                                            <a-select style="width: calc(100% - 10px)"
                                                                      v-model="body.paramSource"
                                                                      :options="sourceOptions"/>
                                                        </a-col>
                                                        <a-col :span="4" v-if="body.paramSource!='param'">
                                                            <a-input style="width: calc(100% - 10px)"
                                                                     :placeholder="i18n('apiEdit.paramValue','参数值')"
                                                                     v-model="body.paramValue"
                                                                     v-if="body.paramSource == 'fixedVar'"/>
                                                            <a-input-group style="width: calc(100% - 10px)"
                                                                           v-if="body.paramSource == 'script'" compact>
                                                                <a-input style="width:75%;" v-model="body.paramValue"
                                                                         :disabled="true"/>
                                                                <a-button @click="openScriptQuery(body)">...</a-button>
                                                            </a-input-group>
                                                            <a-select v-if="body.paramSource=='constantVar'"
                                                                      v-model="body.paramValue"
                                                                      :options="constantField"></a-select>
                                                        </a-col>
                                                        <a-col :span="body.paramSource!='param'?8:12">
                                                            <a-input :placeholder="i18n('apiPreview.remarks','备注')"
                                                                     v-model="body.paramDesc"/>
                                                        </a-col>
                                                        <a-col :span="1">
                                                            <i style="margin-left:5px"
                                                               class="iconfont iconmodal-drag"></i>
                                                            <a-icon style="margin-left:5px" type="delete"
                                                                    @click="deleteData('bodyData',index)"/>
                                                        </a-col>
                                                    </a-row>
                                                </transition-group>
                                            </vuedraggable>
                                        </div>
                                        <div v-if="apiDataType=='json'">
                                            <a-button type="primary" @click="importJson">
                                                {{ i18n('apiEdit.importJson', '导入JSON') }}
                                            </a-button>
                                            <sys-interface-param-recursion :dataSource="bodyDataJson"
                                                                           :bodyDataJson="bodyDataJson" type="body"/>
                                        </div>
                                        <div v-if="apiDataType=='xml'">
                                            <rx-monaco-editor
                                                v-model="bodyDataXml"
                                                style="height:300px;"
                                            >
                                            </rx-monaco-editor>
                                        </div>
                                    </a-form-item>
                                    <a-form-item v-show="paramType=='Query'" >
                                        <a-button type="primary" @click="addQueryParam" style="margin: 10px 0">
                                            {{ i18n('apiEdit.addQueryParamBtn', '添加Query参数') }}
                                        </a-button>
                                        <vuedraggable v-model="queryData">
                                            <transition-group>
                                                <a-row :gutter="[0,10]" :key="index" v-for="(query,index) in queryData"
                                                       style="position:relative">
                                                    <a-col :span="4">
                                                        <a-input class="width10"
                                                                 :placeholder="i18n('apiPreview.paramName','参数名称')"
                                                                 v-model="query.paramName"/>
                                                    </a-col>
                                                    <a-col :span="3">
                                                        <a-select class="widthant" v-model="query.paramRequire"
                                                                  :options="requireOptions"/>
                                                    </a-col>
                                                    <a-col :span="4">
                                                        <a-select class="widthant" v-model="query.paramSource"
                                                                  :options="sourceOptions"/>
                                                    </a-col>
                                                    <a-col :span="4" v-if="query.paramSource!='param'">
                                                        <a-input :placeholder="i18n('apiEdit.paramValue','参数值')"
                                                                 v-model="query.paramValue"
                                                                 v-if="query.paramSource == 'fixedVar'"/>
                                                        <a-input-group v-if="query.paramSource == 'script'" compact>
                                                            <a-input style="width:77%;" v-model="query.paramValue"
                                                                     :disabled="true"/>
                                                            <a-button @click="openScriptQuery(query)">...</a-button>
                                                        </a-input-group>
                                                        <a-select v-if="query.paramSource=='constantVar'"
                                                                  v-model="query.paramValue"
                                                                  :options="constantField"></a-select>
                                                    </a-col>
                                                    <a-col :span="query.paramSource!='param'?6:10">
                                                        <a-input :placeholder="i18n('apiPreview.remarks','备注')"
                                                                 v-model="query.paramDesc"/>
                                                    </a-col>
                                                    <a-col :span="3">
                                                        <i style="margin-left:2px" class="iconfont iconmodal-drag"></i>
                                                        <a-icon style="margin-left: 2px" type="delete"
                                                                @click="deleteData('queryData',index)"/>
                                                    </a-col>
                                                </a-row>
                                            </transition-group>
                                        </vuedraggable>
                                    </a-form-item>
                                    <a-form-item v-show="paramType=='Headers'" >
                                        <a-button type="primary" @click="addHeaderParam" style="margin: 10px 0">
                                            {{ i18n('apiEdit.addHeaderParamBtn', '添加Header参数') }}
                                        </a-button>
                                        <vuedraggable v-model="headerData">
                                            <transition-group>
                                                <a-row :gutter="[0,10]" :key="index" v-for="(header,index) in headerData"
                                                       style="position:relative">
                                                    <a-col :span="5">
                                                        <a-select class="widthant"
                                                                  :placeholder="i18n('apiPreview.paramName','参数名称')"
                                                                  show-search v-model="header.paramName"
                                                                  option-filter-prop="children"
                                                                  :filter-option="filterOption"
                                                                  @focus="fieldFocus(header)"
                                                                  @change="fieldChange($event,header)"
                                                                  @blur="fieldBlur(header)">
                                                            <a-select-option v-for="head in headerDatas" :value="head">
                                                                {{ head }}
                                                            </a-select-option>
                                                        </a-select>
                                                    </a-col>
                                                    <a-col :span="5">
                                                        <a-select class="widthant" v-model="header.paramSource"
                                                                  :options="sourceOptions"/>
                                                    </a-col>
                                                    <a-col :span="5" v-if="header.paramSource!='param'">
                                                        <a-input class="width10"
                                                                 :placeholder="i18n('apiEdit.paramValue','参数值')"
                                                                 v-model="header.paramValue"
                                                                 v-if="header.paramSource == 'fixedVar'"/>
                                                        <a-input-group v-if="header.paramSource == 'script'" compact>
                                                            <a-input style="width:79%;" v-model="header.paramValue"
                                                                     :disabled="true"/>
                                                            <a-button @click="openScriptQuery(header)">...</a-button>
                                                        </a-input-group>
                                                        <a-select v-if="header.paramSource=='constantVar'"
                                                                  v-model="header.paramValue"
                                                                  :options="constantField"></a-select>
                                                    </a-col>
                                                    <a-col :span="header.paramSource!='param'?6:11">
                                                        <a-input :placeholder="i18n('apiPreview.remarks','备注')"
                                                                 v-model="header.paramDesc"/>
                                                    </a-col>
                                                    <a-col :span="3">
                                                        <i style="margin-left:2px" class="iconfont iconmodal-drag"></i>
                                                        <a-icon style="margin-left:2px" type="delete"
                                                                @click="deleteData('headerData',index)"/>
                                                    </a-col>
                                                </a-row>
                                            </transition-group>
                                        </vuedraggable>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </div>
                    </a-collapse-panel>
                </a-collapse>
                <a-collapse style="margin-top: 10px" default-active-key="3" expandIconPosition="right">
                    <a-collapse-panel key="3" :header="i18n('apiEdit.dataProcessSet','数据处理设置')">
                        <a-row  :gutter="[24,12]">
                            <a-col :span="24">
                                <a-form-item style="margin-bottom: 10px" >
                                    <template slot="label">
                                        {{ i18n('apiEdit.returnDataType', '返回数据类型') }}
                                        <a-tooltip>
                                            <template slot="title">
                                                {{ i18n('apiEdit.literature', '参考文献') }}：
                                                <a target="_blank"
                                                    href="http://doc.redxun.cn/docs/jpaas/apiwgReturnDataType"
                                                >
                                                    http://doc.redxun.cn/docs/jpaas/apiwgReturnDataType
                                                </a>
                                            </template>
                                            <a-icon style="margin-top: 4px;" type="question-circle-o"/>
                                        </a-tooltip>
                                    </template>
                                    <a-radio-group v-model="apiReturnType" :options="apiReturnTypeOptions"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="24">
                                <a-form-item style="margin-bottom: 10px;"
                                             :label="i18n('apiEdit.dataProcessType','数据处理类型')">
                                    <a-radio-group v-model="javaType" :options="javaTypeOptions"/>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row v-if="javaType=='script'">
                            <a-col :span="24">
                                <a-form-item :label="i18n('apiEdit.javaScript','JAVA脚本')">
                                    <rx-monaco-editor
                                        v-model="javaCode"
                                        language="java"
                                        style="height:300px;">
                                    </rx-monaco-editor>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row v-show="javaType=='bean'">
                            <a-col :span="24">
                                <a-form-item :label="i18n('apiEdit.dataProcessor','数据处理器')">
                                    <a-popover placement="topLeft" style="max-width: 400px;">
                                        <template slot="content">
                                            <p>{{ i18n('apiEdit.dataProDesc1', '返回数据处理器，在调用接口返回结果后执行。') }}</p>
                                            <p>{{ i18n('apiEdit.dataProDesc2', '需要实现接口') }}:</p>
                                            <p>com.redxun.system.ext.handler.ApiReturnDataHandler</p>
                                            <p>{{ i18n('apiEdit.dataProDesc3', '接口方法') }}：</p>
                                            <p>String analysisText(String data);</p>
                                            <p>
                                                {{ i18n('apiEdit.dataProDesc4', '这里需要配置接口实现类的spring实例Id，这个需要在spring容器进行配置。') }}</p>
                                        </template>
                                        <span slot="title">
                                            {{ i18n('apiEdit.help', '帮助') }}
                                        </span>
                                        <a-input v-decorator="['javaBean']" disabled>
                                            <a-icon slot="addonAfter" type="close" @click="closeHandler"
                                                    style="margin-right:10px;"/>
                                            <a-icon slot="addonAfter" type="setting" @click="addHandler"/>
                                        </a-input>
                                    </a-popover>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-collapse-panel>
                </a-collapse>
                <a-collapse style="margin-top: 10px" default-active-key="4" expandIconPosition="right">
                    <a-collapse-panel key="4" :header="i18n('apiEdit.returnDataSet','返回数据设置')">
                        <div style="text-align: center;margin-bottom: 10px;">
                            <a-radio-group v-model="returnJsonType">
                                <a-radio-button value="model">{{ i18n('apiEdit.formwork', '模板') }}</a-radio-button>
                                     <a-radio-button value="preview" @click="returnJsonChange"> {{ i18n('apiEdit.call', '调用') }}
                                    <a-tooltip>
                                        <template slot="title">
                                            {{ i18n('apiEdit.callDesc', '此预览可以测试接口配置，返回的数据是否正确。') }}
                                        </template>
                                        <a-icon type="question-circle-o"/>
                                    </a-tooltip></a-radio-button>
                            </a-radio-group>
                        </div>
                        <a-row :gutter="12" v-if="returnJsonType=='model'">
                            <a-col :span="24">
                                <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                                    <a-button style="margin-right: 5px" type="primary" @click="importReturnJson">
                                        {{ i18n('apiEdit.importJson', '导入JSON') }}
                                    </a-button>
                                    <a-button type="primary" @click="returnJsonView">
                                        {{ i18n('apiEdit.dataStructure', '数据结构') }}
                                    </a-button>
                                    <sys-interface-param-recursion :dataSource="returnDataJson"
                                                                   :bodyDataJson="returnDataJson" type="return"
                                                                   :apiReturnType="apiReturnType"/>
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-row v-if="returnJsonType=='preview'" style="margin-top: 10px">
                            <a-col :span="24">
                                <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                                    <rx-monaco-editor
                                        v-model="returnJson"
                                        language="json"
                                        style="height:300px;"
                                    >
                                    </rx-monaco-editor>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-collapse-panel>
                </a-collapse>
                <a-row>
                    <a-col :span="24" style="margin-top: 10px">
                        <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1">
                            <a-textarea :placeholder="i18n('apiPreview.remarks','备注')" v-decorator="['description']"
                                        :rows="8"/>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
    </div>
</template>
<script>
import vuedraggable from 'vuedraggable'
import SysInterfaceApiApi from '@/api/system/core/sysInterfaceApi'
import SysInterfaceClassificationApi from "@/api/system/core/sysInterfaceClassification";
import FormCustomQueryApi from '@/api/form/core/formCustomQuery'
import {BaseForm, Util, RxGrid, Dialog, RxMonacoEditor} from "@lowcode/jpaas-common-lib";
import SysInterfaceParamRecursion from "./SysInterfaceParamRecursion";
import SysInterfaceApiHandlerDialog from "./SysInterfaceApiHandlerDialog";
import SysInterfaceApiImportJson from "./SysInterfaceApiImportJson";
import SysInterfaceJson from "./SysInterfaceJson";

export default {
    name: 'SysInterfaceApiEdit',
    mixins: [BaseForm],
    props: ['projectId', 'basePath'],
    components: {
        RxGrid,
        vuedraggable,
        RxMonacoEditor,
        SysInterfaceParamRecursion
    },
    data() {
        return {
            labelCol: {span: 6},
            wrapperCol: {span: 18},
            labelCol1: {span: 4},
            wrapperCol1: {span: 20},
            classificationOptions: [],
            pathParams: [],
            paramTypeOptions: [],
            paramType: '',
            returnJsonType: 'model',
            contentTypeOptions: [],
            apiReturnTypeOptions: [
                {label: this.i18n('apiEdit.not', '无'), value: 'none'},
                {label: 'JSON', value: 'json'},
                {label: 'XML', value: 'xml'}
            ],
            javaTypeOptions: [
                {label: this.i18n('apiEdit.not', '无'), value: 'none'},
                {label: this.i18n('form.script', '脚本'), value: 'script'},
                {label: this.i18n('apiEdit.processor', '处理器'), value: 'bean'}
            ],
            requireOptions: [
                {label: this.i18n('apiEdit.must', '必须'), value: 'YES'},
                {label: this.i18n('apiEdit.notMust', '非必须'), value: 'NO'}
            ],
            sourceOptions: [
                {value: "param", label: this.i18n('apiEdit.paramPassing', '参数传入')},
                {value: "fixedVar", label: this.i18n('form.fixValue', '固定值')},
                {value: "script", label: this.i18n('form.script', '脚本')},
                {value: "constantVar", label: this.i18n('form.constant', '常量')}
            ],
            constantField: [],
            apiDataType: '',
            javaType: '',
            apiReturnType: '',
            apiType: '',
            bodyData: [{paramName: '', paramRequire: 'YES', paramSource: 'param', paramValue: '', paramDesc: ''}],
            queryData: [{paramName: '', paramRequire: 'YES', paramSource: 'param', paramValue: '', paramDesc: ''}],
            headerData: [{paramName: '', paramSource: 'param', paramValue: '', paramDesc: ''}],
            headerDatas: ["Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language", "Accept-Datetime", "Authorization", "Cache-Control", "Connection", "Cookie", "Content-Disposition",
                "Content-Length", "Content-MD5", "Content-Type", "Date", "Expect", "From", "Host", "If-Match", "If-Modified-Since", "If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards",
                "Origin", "Pragma", "Proxy-Authorization", "Range", "Referer", "TE", "User-Agent", "Upgrade", "Via", "Warning", "X-Requested-With", "DNT", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto",
                "Front-End-Https", "X-Http-Method-Override", "X-ATT-DeviceId", "X-Wap-Profile", "Proxy-Connection", "X-UIDH", "X-Csrf-Token","token"],
            curHeader: {},
            dataJson: [{
                paramName: 'root',
                caret: 'down',
                isRoot: true,
                paramType: 'object',
                paramSource: 'none',
                paramDesc: '',
                children: []
            }],
            bodyDataJson: [],
            bodyDataXml: '',
            returnDataJson: [],
            returnJson: '',
            javaCode: ''
        }
    },
    created() {
        this.loadConstants();
        this.loadClassification();
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysInterfaceProject", key);
        },
        onload_(values) {
            this.apiDataType = values.apiDataType || 'form';
            this.javaType = values.javaType || 'none';
            this.apiReturnType = values.apiReturnType || 'none';
            this.apiType = values.apiType;
            if (this.apiType == 'SOAP') {
                values.apiMethod = 'POST';
                this.apiDataType = 'xml';
            }
            this.javaCode = values.javaCode || `import com.alibaba.fastjson.JSONObject;
                import com.alibaba.fastjson.JSONArray;
                //` + this.i18n('apiEdit.scriptText', '解析文本数据,返回json/xml字符串') + `
                String analysisText(String data) {
                    //data:{content:"返回数据",query:{请求参数}}
                    JSONObject json = JSONObject.parseObject(data);
                    String content = json.getString("content");
                    return content;
                }`;
            //初始化数据
            this.returnJsonType = 'model';
            this.bodyDataXml = '';
            this.bodyDataJson = [];
            this.bodyData = [{paramName: '', paramRequire: 'YES', paramSource: 'param', paramValue: '', paramDesc: ''}];
            this.queryData = [{
                paramName: '',
                paramRequire: 'YES',
                paramSource: 'param',
                paramValue: '',
                paramDesc: ''
            }];
            this.headerData = [{paramName: '', paramSource: 'param', paramValue: '', paramDesc: ''}];
            if (this.apiDataType == 'form') {
                if (values.apiBody && values.apiBody != '[]') {
                    this.bodyData = JSON.parse(values.apiBody);
                }
                this.bodyDataJson = Util.deepClone(this.dataJson);
            } else if (this.apiDataType == 'json') {
                if (values.apiBody && values.apiBody != '[]') {
                    this.bodyDataJson = JSON.parse(values.apiBody);
                } else {
                    this.bodyDataJson = Util.deepClone(this.dataJson);
                }
            } else if (this.apiDataType == 'xml') {
                this.bodyDataXml = values.apiBody;
                this.bodyDataJson = Util.deepClone(this.dataJson);
            }
            if (values.apiReturnFields && values.apiReturnFields != '[]') {
                this.returnDataJson = JSON.parse(values.apiReturnFields);
            } else {
                this.returnDataJson = Util.deepClone(this.dataJson);
            }
            if (values.apiPathParams && values.apiPathParams != '[]') {
                this.pathParams = JSON.parse(values.apiPathParams);
            } else {
                this.pathParams = [];
                this.changeApiPath({target: {value: values.apiPath}});
            }
            if (values.apiHeaders && values.apiHeaders != '[]') {
                this.headerData = JSON.parse(values.apiHeaders);
            }
            if (values.apiQuery && values.apiQuery != '[]') {
                this.queryData = JSON.parse(values.apiQuery);
            }
            this.contentTypeChange(this.apiType);
            this.methodChange(values.apiMethod);
        },
        get(id) {
            return SysInterfaceApiApi.get(id);
        },
        save(values) {
            values.apiPathParams = JSON.stringify(this.pathParams);
            values.apiHeaders = JSON.stringify(this.parseHeaderData(this.parseEmptyData(this.headerData), values.apiMethod));
            values.apiQuery = JSON.stringify(this.parseEmptyData(this.queryData));
            if (this.apiDataType == 'form') {
                values.apiBody = JSON.stringify(this.parseEmptyData(this.bodyData));
            } else if (this.apiDataType == 'json') {
                values.apiBody = JSON.stringify(this.parseEmptyData(this.bodyDataJson));
            } else if (this.apiDataType == 'xml') {
                values.apiBody = this.bodyDataXml;
            }
            values.apiDataType = this.apiDataType;
            values.apiReturnType = this.apiReturnType;
            values.apiReturnFields = JSON.stringify(this.parseEmptyData(this.returnDataJson));
            values.javaType = this.javaType;
            values.javaCode = this.javaCode;
            return SysInterfaceApiApi.save(values);
        },
        parseApiDataType(apiMethod) {
            if (apiMethod == 'GET' || this.apiDataType == 'form') {
                return 'application/x-www-form-urlencoded';
            } else if (this.apiDataType == 'json') {
                return 'application/json';
            } else if (this.apiDataType == 'xml') {
                return 'text/xml';
            }
            return '';
        },
        parseHeaderData(data, apiMethod) {
            var isExist = false;
            data.forEach(item => {
                if (item.paramName == 'Content-Type') {
                    // let value=this.parseApiDataType(apiMethod);
                    // if(item.paramValue.indexOf(value)==-1) {
                    //     item.paramSource = 'fixedVar';
                    //     item.paramValue = value + ';charset=UTF-8';
                    // }
                    isExist = true;
                }
            })
            if (!isExist) {
                data.splice(0, 0, {
                    paramName: 'Content-Type',
                    paramSource: 'fixedVar',
                    paramValue: this.parseApiDataType(apiMethod) + ';charset=UTF-8',
                    paramDesc: ''
                });
            }
            return data;
        },
        parseEmptyData(data) {
            var array = [];
            data.forEach(item => {
                if (!Util.isEmpty(item.paramName)) {
                    array.push(item);
                }
                if (item.children) {
                    item.children = this.parseEmptyData(item.children);
                }
            })
            return array;
        },
        handlerSave() {
            this.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                this.confirmLoading = true;
                this.save(values).then(res => {
                    if (res.success && res.code == 200) {
                        //返回结果数据。
                        this.resultData = res.data;
                        this.onload_(this.resultData);
                    }
                }).catch(() => {
                    this.$message.error(this.$ti18('rxMsa.sysError', '系统错误，请稍后再试!'))
                }).finally(() => {
                    this.confirmLoading = false
                })
            })
        },
        loadConstants() {
            FormCustomQueryApi.getConstants().then((data) => {
                this.constantField = this.constantField.concat(
                    data.map((item) => {
                        return {label: item.val, value: item.key}
                    })
                )
            })
        },
        loadClassification() {
            var self_ = this;
            SysInterfaceClassificationApi.queryByProjectId(this.projectId).then(data => {
                self_.classificationOptions = data.map(item => {
                    return {label: item.classificationName, value: item.classificationId};
                })
            })
        },
        changeApiPath(e) {
            var pathParams = Util.deepClone(this.pathParams);
            this.pathParams = [];
            var value = e.target.value;
            var arr = [];
            var myregexp = /\${(.*?)}/g;
            var match = myregexp.exec(value);
            while (match != null) {
                arr.push(match[1]);
                match = myregexp.exec(value);
            }
            for (let i = 0; i < arr.length; i++) {
                //是否添加
                var falg = true;
                if (!arr[i]) {
                    falg = false;
                }
                for (let j = 0; j < this.pathParams.length; j++) {
                    if (arr[i] == this.pathParams[j].paramName) {
                        falg = false;
                    }
                }
                if (falg) {
                    this.pathParams.push({
                        paramName: arr[i],
                        paramSource: "param",
                        paramValue: pathParams[i] ? pathParams[i].paramValue : "",
                        paramDesc: pathParams[i] ? pathParams[i].paramDesc : ""
                    })
                }
            }
        },
        contentTypeChange(value) {
            if (value == 'SOAP') {
                this.contentTypeOptions = [
                    {label: 'xml', value: 'xml'}
                ]
            } else {
                this.contentTypeOptions = [
                    {label: 'form', value: 'form'},
                    {label: 'json', value: 'json'}
                ]
            }
        },
        apiTypeChange(value) {
            this.apiType = value;
            var apiMethod = this.form.getFieldValue("apiMethod");
            if (value == 'SOAP') {
                apiMethod = 'POST';
                this.apiDataType = 'xml';
            } else {
                this.apiDataType = 'form';
            }
            this.contentTypeChange(value);
            this.methodChange(apiMethod);
        },
        methodChange(value) {
            this.paramTypeOptions = [
                {label: 'Body', value: 'Body'},
                {label: 'Query', value: 'Query'},
                {label: 'Headers', value: 'Headers'}
            ]
            if (value == 'GET') {
                this.paramType = 'Query';
            } else {
                this.paramType = 'Body';
            }
        },
        openScriptQuery(record) {
            Dialog.openScripttextDialog(
                {
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    data: {script: record.paramValue},
                },
                function (self, data) {
                    record.paramValue = data
                }
            )
        },
        addFormParam() {
            this.bodyData.push({
                paramName: '',
                paramRequire: 'YES',
                paramSource: 'param',
                paramValue: '',
                paramDesc: ''
            })
        },
        addQueryParam() {
            this.queryData.push({
                paramName: '',
                paramRequire: 'YES',
                paramSource: 'param',
                paramValue: '',
                paramDesc: ''
            })
        },
        addHeaderParam() {
            this.headerData.push({paramName: '', paramSource: 'param', paramValue: '', paramDesc: ''})
        },
        filterOption(input, option) {
            this.curHeader["searchField"] = {label: input, key: input, change: true};
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            );
        },
        fieldFocus(record) {
            this.curHeader = record;
        },
        fieldBlur(record) {
            if (record["searchField"] && record["searchField"].change) {
                record["searchField"].change = false;
                var text = record["searchField"].key;
                record.paramName = text;
                this.fieldChange(text, record);
            }
        },
        fieldChange(value, record) {
            if (record["searchField"] && record["searchField"].change) {
                record["searchField"].change = false;
            }
        },
        parseDataJson(json, isRoot, paramName, defaultSource) {
            var obj = this.getNewNode(defaultSource);
            var result = [obj];
            obj.paramName = paramName;
            if (isRoot) {
                obj.caret = 'down';
                obj.isRoot = true;
            }
            if (json) {
                if (json.constructor == Object) {
                    obj.paramType = 'object';
                    obj.caret = 'down';
                    for (var key in json) {
                        obj.children.push(...this.parseDataJson(json[key], false, key, defaultSource));
                    }
                } else if (json.constructor == Array) {
                    obj.paramType = 'array';
                    var node = this.getNewNode(defaultSource);
                    obj.caret = 'down';
                    node.paramName = 'items';
                    node.paramRequire = false;
                    node.isChild = true;
                    obj.children.push(node);
                    var global = {};
                    if (json.length > 0) {
                        var child = this.parseDataJson(json[0], false, '', defaultSource);
                        node.caret = child[0].caret;
                        node.paramType = child[0].paramType;
                        node.children = child[0].children;
                    }
                } else if (json.constructor == Number) {
                    obj.paramType = 'number';
                    obj.paramValue = json;
                } else if (json.constructor == Boolean) {
                    obj.paramType = 'boolean';
                    obj.paramValue = json;
                }
            } else {
                obj.paramValue = json;
            }
            return result;
        },
        getNewNode(source) {
            return {
                paramName: '',
                caret: '',
                paramRequire: true,
                paramType: 'string',
                paramSource: source,
                paramValue: '',
                paramDesc: '',
                children: []
            };
        },
        importJson() {
            var self = this;
            Util.open({
                component: SysInterfaceApiImportJson,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: self.i18n('apiEdit.importJson', '导入JSON')
            }, function (action, data) {
                if (action != 'ok') {
                    return;
                }
                self.bodyDataJson = self.parseDataJson(data, true, 'root', 'fixedVar');
            });
        },
        getReturnJson(root) {
            if (root.paramType == 'object') {
                var obj = {};
                for (var i = 0; i < root.children.length; i++) {
                    var child = root.children[i];
                    obj[child.paramName] = this.getReturnJson(child);
                }
                return obj;
            } else if (root.paramType == 'array') {
                var array = [];
                array.push(this.getReturnJson(root.children[0]));
                return array;
            } else if (root.paramType == 'number') {
                return 0;
            } else if (root.paramType == 'boolean') {
                return false;
            } else {
                return "";
            }
        },
        returnJsonView() {
            var json = this.getReturnJson(this.returnDataJson[0]);
            var baseConf = {
                curVm: this,
                component: SysInterfaceJson,
                title: this.i18n('apiEdit.jsonData', 'JSON数据'),
                widthHeight: ['800px', '700px'],
                data: {
                    json: json,
                    callback: function (data) {
                        console.info(data)
                    },
                },
            }
            Util.open(baseConf, function (action) {
            })
        },
        importReturnJson() {
            var self = this;
            Util.open({
                component: SysInterfaceApiImportJson,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: self.i18n('apiEdit.importJson', '导入JSON')
            }, function (action, data) {
                if (action != 'ok') {
                    return;
                }
                self.returnDataJson = self.parseDataJson(data, true, 'root', 'none');
            });
        },
        returnJsonChange() {
            var self = this;
            this.form.validateFields((err, values) => {
                if (err) {
                    return;
                }
                values.apiPathParams = JSON.stringify(self.pathParams);
                values.apiHeaders = JSON.stringify(self.parseHeaderData(self.parseEmptyData(self.headerData), values.apiMethod));
                values.apiQuery = JSON.stringify(self.parseEmptyData(self.queryData));
                if (self.apiDataType == 'form') {
                    values.apiBody = JSON.stringify(self.parseEmptyData(self.bodyData));
                } else if (self.apiDataType == 'json') {
                    values.apiBody = JSON.stringify(self.parseEmptyData(self.bodyDataJson));
                } else if (self.apiDataType == 'xml') {
                    values.apiBody = self.bodyDataXml;
                }
                values.apiDataType = self.apiDataType;
                values.apiReturnType = self.apiReturnType;
                values.apiReturnFields = JSON.stringify(self.parseEmptyData(self.returnDataJson));
                values.javaType = self.javaType;
                values.javaCode = self.javaCode;
                values.projectId = self.projectId;
                SysInterfaceApiApi.executeTestApi(values).then(res => {
                    if (res.success) {
                        self.returnJson = JSON.stringify(res.data);
                    }
                })
            })
        },
        addHandler() {
            var self_ = this;
            Util.open({
                component: SysInterfaceApiHandlerDialog,
                curVm: this,
                widthHeight: ['800px', '600px'],
                title: self_.i18n('apiEdit.dataHandlerTitle', '选择返回数据处理器')
            }, function (action, data) {
                if (action != 'ok') {
                    return;
                }
                self_.form.setFieldsValue({'javaBean': data.value});
            });
        },
        closeHandler() {
            this.form.setFieldsValue({'javaBean': ''});
        },
        deleteData(name, index) {
            this[name].splice(index, 1);
        }
    }
}
</script>
<style>
.sysinterface > div:nth-child(1) {
    border-bottom: 1px solid #e6e8eb;
    text-align: right;
    background: white;
    height: 45px;
}

.sysinterface > div:nth-child(2) {
    flex: 1;
    overflow: auto;
    margin-bottom: 40px;
}

.sysinterface {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    padding: 0px 10px 0px 10px;
}

.width10 {
    width: calc(100% - 10px);
}

.widthant .ant-select-selection--single {
    width: calc(100% - 10px);
}

.interface-title {
    clear: both;
    font-weight: 400;
    margin-bottom: .16rem;
    border-left: 3px solid #2395f1;
    padding-left: 8px;
}

.basePath .ant-input-group-addon {
    display: none;
}
.sysinterface .ant-form-item,
.rx-sys-form  .ant-form-item{
    margin-bottom: 0;
}
</style>
